package com.store.app.activity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.util.Pair;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.hyphenate.EMCallBack;
import com.hyphenate.EMMessageListener;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMConversation;
import com.hyphenate.chat.EMMessage;
import com.hyphenate.easeui.model.DBHelper_hy;
import com.hyphenate.easeui.model.EaseAtMessageHelper;
import com.hyphenate.easeui.model.HyUserDao;
import com.hyphenate.easeui.model.UserEventBean;
import com.hyphenate.easeui.model.recordBean_hy;
import com.hyphenate.easeui.widget.EaseConversationList;
import com.store.app.BaseActivity;
import com.store.app.ExitApplication;
import com.store.app.R;
import com.store.app.bean.HXUserBean;
import com.store.app.hyphenate.Constant;
import com.store.app.hyphenate.HyphenateHelper;
import com.store.app.hyphenate.db.InviteMessgeDao;
import com.store.app.imlife.activity.ChatActivity;
import com.store.app.imlife.activity.LiveCameraActivity;
import com.store.app.net.NetRequest;
import com.store.app.net.ifc.IOnHttpListener;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import de.greenrobot.event.EventBus;

/**
 * 消息界面
 * Created by Ben
 * on 2016/8/19 0019.\
 */
public class MessageDispitchActivity extends BaseActivity implements IOnHttpListener {
    private NetRequest netRequest;
    private ImageView public_ll_return;
    private TextView tvTitle;
    protected List<EMConversation> conversationList = new ArrayList<EMConversation>();
    protected EaseConversationList conversationListView;
    private LinearLayout ll_create_onlive;
    private LinearLayout ll_create_group;
    //数据库存储
    private DBHelper_hy db = null;
    private recordBean_hy rb = null;
    private RelativeLayout my_group_layout;
    //首页消息红点 1为是 0为不是
    SharedPreferences preferences;
    SharedPreferences.Editor editor;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ExitApplication.getInstance().addActivity(this);
        setContentView(R.layout.activity_msg_dispitch);
        preferences= android.preference.PreferenceManager.getDefaultSharedPreferences(this);
        editor= preferences.edit();
        EventBus.getDefault().register(this);
        if (db == null) {
            db = new DBHelper_hy(this);
            rb = new recordBean_hy();
        }
        netRequest = new NetRequest(this);
        initView();
        inithyList();
        if (!EMClient.getInstance().isLoggedInBefore() || !EMClient.getInstance().isConnected()) {
            String im_id = preferences.getString("im_user_id", "");

            if (!TextUtils.isEmpty(im_id)) {
                if (!TextUtils.isEmpty(im_id)) {
                    Log.i("mylog", "重连环信");
                    login(im_id);
                }
            }
        }

    }

    public void login(final String s_name) {
        EMClient.getInstance().login(s_name, s_name, new EMCallBack() {

            @Override
            public void onSuccess() {
                Log.v("zyl", "登录环信成功");
                EMClient.getInstance().groupManager().loadAllGroups();
                EMClient.getInstance().chatManager().loadAllConversations();
            }

            @Override
            public void onProgress(int progress, String status) {
                Log.d("mylog", "login: " + progress);
            }

            @Override
            public void onError(final int code, final String message) {
                Log.v("zyl", "登录环信失败");
                loginAgain(s_name);
            }
        });
    }

    //登录错误的情况下先调退出接口再登录一次
    public void loginAgain(final String s_name) {
        HyphenateHelper.getInstance().logout(false, new EMCallBack() {
            @Override
            public void onSuccess() {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                EMClient.getInstance().login(s_name, s_name, new EMCallBack() {

                    @Override
                    public void onSuccess() {
                        Log.i("zyl", "再次登录环信成功");
                        // ** manually load all local groups and conversation
                        EMClient.getInstance().groupManager().loadAllGroups();
                        EMClient.getInstance().chatManager().loadAllConversations();

                    }

                    @Override
                    public void onProgress(int progress, String status) {
                    }

                    @Override
                    public void onError(final int code, final String message) {

                    }
                });
            }

            @Override
            public void onProgress(int progress, String status) {

            }

            @Override
            public void onError(int code, String message) {

            }
        });
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);

    }

    @Override
    public void onResume() {
        super.onResume();
        conversationList.clear();
        conversationList.addAll(loadConversationList());
        conversationListView.refresh();
    }

    @Override
    public void onPause() {
        super.onPause();
//        if(editor!=null){
//            editor.putInt("mainmess", 0).apply();
//        }
    }

    private void inithyList() {
        conversationList.addAll(loadConversationList());
        conversationListView.init(conversationList);
        conversationListView.setDivider(null);
        conversationListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if(position==0){
                    Intent intent = new Intent(MessageDispitchActivity.this, MessageActivity.class);
                    startActivity(intent);
                }else if(position==1) {
                    String chatid = "diandongzhushouserviceagent";
                    String title  ="官方客服";
                    Intent intent = new Intent(MessageDispitchActivity.this, ChatActivity.class);
                    intent.putExtra("userId", chatid);
                    intent.putExtra("groupName", title);
                    startActivity(intent);
                    try {
                        rb.saveMember(db, "", chatid, title
                                , "","https://oss-img.meitianhui.com/communityDocs/kefu.jpg", "0");
                    }catch (Exception e){
                    }
                }else if(position==2){
                    Intent intent = new Intent(MessageDispitchActivity.this, MyGroupActivity.class);
                    startActivity(intent);
                }

                else{
                EMConversation conversation = conversationListView.getItem(position-3);
                String username = conversation.conversationId();
                if (username.equals(EMClient.getInstance().getCurrentUser()))
                    Toast.makeText(MessageDispitchActivity.this, R.string.Cant_chat_with_yourself, Toast.LENGTH_SHORT).show();
                else {
                    // start chat acitivity
                    Intent intent = new Intent(MessageDispitchActivity.this, ChatActivity.class);
                    if (conversation.isGroup()) {
                        if (conversation.getType() == EMConversation.EMConversationType.ChatRoom) {
                            // it's group chat
                            intent.putExtra(Constant.EXTRA_CHAT_TYPE, Constant.CHATTYPE_CHATROOM);
                        } else {
                            intent.putExtra(Constant.EXTRA_CHAT_TYPE, Constant.CHATTYPE_GROUP);
                        }
                    }else{
                        HyUserDao hyUserDao = rb.findMember_other(db, username);
                        if (hyUserDao != null) {
                            String nickname = hyUserDao.getNickname();
                            if(!TextUtils.isEmpty(nickname)){
                                intent.putExtra("groupName", nickname);
                            }
                        }
                    }
                    // it's single chat
                    intent.putExtra(Constant.EXTRA_USER_ID, username);
                    startActivity(intent);
                }
            }}
        });
        conversationListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {
                if(position!=0&&position!=1&&position!=2) {
                    new AlertDialog.Builder(MessageDispitchActivity.this)
                            .setItems(new String[]{"删除本条记录", "删除本条记录和聊天记录"},
                                    new DialogInterface.OnClickListener() {

                                        @Override
                                        public void onClick(DialogInterface dialog,
                                                            int which) {

                                            EMConversation tobeDeleteCons = conversationListView.getItem(position-3);
                                            if (tobeDeleteCons == null) {
                                                dialog.dismiss();
                                                return;
                                            }
                                            if (tobeDeleteCons.getType() == EMConversation.EMConversationType.GroupChat) {
                                                EaseAtMessageHelper.get().removeAtMeGroup(tobeDeleteCons.conversationId());
                                            }

                                            if (which == 1) {
                                                try {
                                                    // delete conversation
                                                    EMClient.getInstance().chatManager().deleteConversation(tobeDeleteCons.conversationId(), true);
                                                    InviteMessgeDao inviteMessgeDao = new InviteMessgeDao(MessageDispitchActivity.this);
                                                    inviteMessgeDao.deleteMessage(tobeDeleteCons.conversationId());
                                                } catch (Exception e) {
                                                    e.printStackTrace();
                                                }

                                            } else if (which == 0) {
                                                try {
                                                    // delete conversation
                                                    EMClient.getInstance().chatManager().deleteConversation(tobeDeleteCons.conversationId(), false);
                                                    InviteMessgeDao inviteMessgeDao = new InviteMessgeDao(MessageDispitchActivity.this);
                                                    inviteMessgeDao.deleteMessage(tobeDeleteCons.conversationId());
                                                } catch (Exception e) {
                                                    e.printStackTrace();
                                                }
                                            }
                                            conversationList.clear();
                                            conversationList.addAll(loadConversationList());
                                            conversationListView.refresh();
                                        }
                                    }).show();
                }
                return true;
            }
        });

        EMClient.getInstance().chatManager().addMessageListener(messageListener);
    }
//    private void setData() {
//        application=(MeiTianHuiApplication) getApplication();
//        userToken=application.userToken;
//        netRequest.requestHXGroupList(1, userToken, userToken.getIm_user_id());
//
//    }


    protected void initView() {
        conversationListView = (EaseConversationList) findViewById(R.id.hymessage_listview);
        /*findViewById(R.id.sys_msg_layout).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });*/
//
//        //点击加群
//        findViewById(R.id.addgroup).setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                String groupid = "";//群id自己填
////                netRequest.requestHXAddSingleUserToChatGroup(2, userToken, userToken.getIm_user_id(), "234584344214110640");
//
//            }
//        });
//        //点击创建
//        findViewById(R.id.creategroup).setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
////                netRequest.requestHXCreateGroup(3, userToken, "每天惠装B群", "欢迎每天惠技术成员加入", userToken.getIm_user_id());
//            }
//        });

        public_ll_return = (ImageView) findViewById(R.id.public_ll_return);
        public_ll_return.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                finish();
            }
        });
        tvTitle = (TextView) findViewById(R.id.tvTitle);
        tvTitle.setText("消息");
        ll_create_onlive = (LinearLayout) findViewById(R.id.ll_create_onlive);
        ll_create_onlive.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!EMClient.getInstance().isLoggedInBefore() || !EMClient.getInstance().isConnected()) {
                    Toast.makeText(MessageDispitchActivity.this,"创建直播失败，请重新登录！",Toast.LENGTH_SHORT).show();
                    return;
                }

                Intent intent = new Intent(MessageDispitchActivity.this, LiveCameraActivity.class);
                startActivity(intent);

            }
        });
        ll_create_group = (LinearLayout) findViewById(R.id.ll_create_group);
        ll_create_group.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.v("zyl","EMClient.getInstance().isLoggedInBefore():"+EMClient.getInstance().isLoggedInBefore());
                Log.v("zyl","EMClient.getInstance().isConnected():"+EMClient.getInstance().isConnected());
                if (!EMClient.getInstance().isLoggedInBefore() || !EMClient.getInstance().isConnected()) {
                    Toast.makeText(MessageDispitchActivity.this,"创建群组失败,请重新登录！",Toast.LENGTH_SHORT).show();
                    return;
                }
                Intent intent = new Intent(MessageDispitchActivity.this, AddContactsActivity.class);
                intent.putExtra("type",0);
                startActivity(intent);
            }
        });
        /*my_group_layout = (RelativeLayout) findViewById(R.id.my_group_layout);
        my_group_layout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });*/
    }


    @Override
    public void onAfinalFail() {

    }

    @Override
    public void onExecuteSuccess(int requestId, String result, String msg) {
       if (requestId == 2) {
            Gson gson = new Gson();
            HXUserBean hxUserBean = gson.fromJson(result, HXUserBean.class);
            try {
                if (rb.saveMember(db, "", hxUserBean.getIm_user_id(), hxUserBean.getNickname()
                        , "", hxUserBean.getHead_pic_path(), "0")) {
                    new Thread() {
                        public void run() {
                            try {
                                Thread.sleep(500);
                                runOnUiThread(new Runnable() {
                                    public void run() {
                                        conversationList.clear();
                                        conversationList.addAll(loadConversationList());
                                        conversationListView.refresh();
                                    }

                                });
                            } catch (Exception e) {
                            }
                        }
                    }.start();
                }
            } catch (Exception e) {

            }
        }
    }

    @Override
    public void onExecuteFail(int requestId, String msg) {
        Log.i("mylog", msg);
    }

    /**
     * load conversation list
     *
     * @return +
     */
    protected List<EMConversation> loadConversationList() {
        // get all conversations
        Map<String, EMConversation> conversations = EMClient.getInstance().chatManager().getAllConversations();
        List<Pair<Long, EMConversation>> sortList = new ArrayList<Pair<Long, EMConversation>>();
        /**
         * lastMsgTime will change if there is new message during sorting
         * so use synchronized to make sure timestamp of last message won't change.
         */
        synchronized (conversations) {
            for (EMConversation conversation : conversations.values()) {
                if (conversation.getAllMessages().size() != 0) {
                    if(conversation.getType()!= EMConversation.EMConversationType.ChatRoom) {
                        sortList.add(new Pair<Long, EMConversation>(conversation.getLastMessage().getMsgTime(), conversation));
                    }
                }
            }
        }
        try {
            // Internal is TimSort algorithm, has bug
            sortConversationByLastChatTime(sortList);
        } catch (Exception e) {
            e.printStackTrace();
        }
        List<EMConversation> list = new ArrayList<EMConversation>();
        for (Pair<Long, EMConversation> sortItem : sortList) {
            list.add(sortItem.second);
        }
        return list;
    }

    /**
     * sort conversations according time stamp of last message
     *
     * @param conversationList
     */
    private void sortConversationByLastChatTime(List<Pair<Long, EMConversation>> conversationList) {
        Collections.sort(conversationList, new Comparator<Pair<Long, EMConversation>>() {
            @Override
            public int compare(final Pair<Long, EMConversation> con1, final Pair<Long, EMConversation> con2) {

                if (con1.first == con2.first) {
                    return 0;
                } else if (con2.first > con1.first) {
                    return 1;
                } else {
                    return -1;
                }
            }

        });
    }
    HashMap<String,String> map_noimg=new HashMap<>();
    public void onEvent(UserEventBean bean) {
        int type = bean.type;
        if (type == 0) {
            if(map_noimg.get(bean.username)==null) {
                map_noimg.put(bean.username,bean.username);
                Log.i("zyl","aa");
                //单聊查询用户信息
                netRequest.requestHXIMUserDetail(2, bean.username);
            }
        }
    }
    EMMessageListener messageListener = new EMMessageListener() {

        @Override
        public void onMessageReceived(List<EMMessage> messages) {
            // notify new message
            conversationList.clear();
            conversationList.addAll(loadConversationList());
            conversationListView.refresh();
        }

        @Override
        public void onCmdMessageReceived(List<EMMessage> messages) {
            //red packet code : 处理红包回执透传消息

        }

        @Override
        public void onMessageRead(List<EMMessage> list) {

        }

        @Override
        public void onMessageDelivered(List<EMMessage> list) {

        }


        @Override
        public void onMessageChanged(EMMessage message, Object change) {}
    };
}
